package com.hello.system.controller;

import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.hello.common.log.annotation.Log;
import com.hello.common.log.enums.BusinessType;
import com.hello.common.security.annotation.RequiresPermissions;
import com.hello.common.core.utils.StringUtils;
import com.hello.common.core.utils.file.FileTypeUtils;
import com.hello.common.core.utils.file.MimeTypeUtils;
import com.hello.system.domain.RentalDevices;
import com.hello.system.domain.vo.RentalDeviceWithInventoryVo;
import com.hello.system.service.IRentalDevicesService;
import com.hello.system.service.ISysFileService;
import com.hello.common.core.web.controller.BaseController;
import com.hello.common.core.web.domain.AjaxResult;
import com.hello.common.core.utils.poi.ExcelUtil;
import com.hello.common.core.web.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 设备Controller
 * 
 * @author hello
 * @date 2025-07-20
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/devices")
public class RentalDevicesController extends BaseController
{
    private final IRentalDevicesService rentalDevicesService;
    private final ISysFileService sysFileService;

    /**
     * 查询设备列表
     */
    // @RequiresPermissions("system:devices:list")
    @GetMapping("/list")
    public TableDataInfo list(RentalDevices rentalDevices)
    {
        log.info("======== 查询设备列表请求 ========");
        log.info("请求参数: {}", rentalDevices);
        
        startPage();
        List<RentalDevices> list = rentalDevicesService.selectRentalDevicesList(rentalDevices);
        TableDataInfo result = getDataTable(list);
        
        log.info("查询结果: 总记录数={}, 当前页数据量={}", result.getTotal(), list.size());
        log.info("======== 查询设备列表完成 ========");
        
        return result;
    }

    /**
     * 查询设备列表（带库存信息）
     */
    @GetMapping("/list-with-inventory")
    public TableDataInfo listWithInventory(RentalDevices rentalDevices)
    {
        log.info("======== 查询设备列表（带库存信息）请求 ========");
        log.info("请求参数: {}", rentalDevices);
        
        
        startPage();
        List<RentalDeviceWithInventoryVo> list = rentalDevicesService.selectRentalDevicesWithInventoryList(rentalDevices);
        TableDataInfo result = getDataTable(list);
        
        log.info("查询结果: 总记录数={}, 当前页数据量={}", result.getTotal(), list.size());
        log.info("======== 查询设备列表（带库存信息）完成 ========");
        
        return result;
    }

    /**
     * 导出设备列表
     */
    // @RequiresPermissions("system:devices:export")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RentalDevices rentalDevices)
    {
        log.info("======== 导出设备数据请求 ========");
        log.info("导出条件: {}", rentalDevices);
        
        List<RentalDevices> list = rentalDevicesService.selectRentalDevicesList(rentalDevices);
        log.info("导出数据量: {} 条记录", list.size());
        
        ExcelUtil<RentalDevices> util = new ExcelUtil<RentalDevices>(RentalDevices.class);
        util.exportExcel(response, list, "设备数据");
        
        log.info("======== 设备数据导出完成 ========");
    }

    /**
     * 获取设备详细信息
     */
    // @RequiresPermissions("system:devices:query")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId)
    {
        log.info("======== 获取设备详情请求 ========");
        log.info("设备ID: {}", deviceId);
        
        RentalDevices device = rentalDevicesService.selectRentalDevicesByDeviceId(deviceId);
        log.info("查询结果: {}", device != null ? "找到设备信息" : "未找到对应设备");
        
        log.info("======== 获取设备详情完成 ========");
        return success(device);
    }

    /**
     * 新增设备
     */
    // @RequiresPermissions("system:devices:add")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RentalDevices rentalDevices)
    {
        log.info("======== 新增设备请求 ========");
        log.info("新增数据: {}", rentalDevices);
        
        int result = rentalDevicesService.insertRentalDevices(rentalDevices);
        log.info("新增结果: {}", result > 0 ? "成功" : "失败");
        
        log.info("======== 新增设备完成 ========");
        return toAjax(result);
    }

    /**
     * 修改设备
     */
    // @RequiresPermissions("system:devices:edit")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RentalDevices rentalDevices)
    {
        log.info("======== 修改设备请求 ========");
        log.info("修改数据: {}", rentalDevices);
        
        int result = rentalDevicesService.updateRentalDevices(rentalDevices);
        log.info("修改结果: {}", result > 0 ? "成功" : "失败");
        
        log.info("======== 修改设备完成 ========");
        return toAjax(result);
    }

    /**
     * 删除设备
     */
    // @RequiresPermissions("system:devices:remove")    
    @Log(title = "设备", businessType = BusinessType.DELETE)
	@DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable Long[] deviceIds)
    {
        log.info("======== 删除设备请求 ========");
        log.info("删除设备ID列表: {}", java.util.Arrays.toString(deviceIds));
        log.info("删除数量: {} 个设备记录", deviceIds.length);
        
        int result = rentalDevicesService.deleteRentalDevicesByDeviceIds(deviceIds);
        log.info("删除结果: {}", result > 0 ? "成功" : "失败");
        
        log.info("======== 删除设备完成 ========");
        return toAjax(result);
    }

    /**
     * 设备图片上传
     */
    @Log(title = "设备图片", businessType = BusinessType.UPDATE)
    @PostMapping("/upload-image")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file)
    {
        log.info("======== 设备图片上传请求 ========");
        log.info("上传文件名: {}", file.getOriginalFilename());
        log.info("文件大小: {} bytes", file.getSize());
        
        if (file.isEmpty())
        {
            log.warn("上传文件为空");
            return error("上传文件不能为空");
        }
        
        // 检查文件类型
        String extension = FileTypeUtils.getExtension(file);
        if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION))
        {
            log.warn("文件格式不正确: {}", extension);
            return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
        }
        
        try {
            String url = sysFileService.uploadFile(file);
            if (StringUtils.isEmpty(url))
            {
                log.error("文件上传失败，返回URL为空");
                return error("文件上传失败，请联系管理员");
            }
            
            log.info("文件上传成功，URL: {}", url);
            log.info("======== 设备图片上传完成 ========");
            
            // 返回成功结果，直接将URL作为data返回
            return AjaxResult.success("上传成功", url);
        } catch (Exception e) {
            log.error("文件上传异常: {}", e.getMessage(), e);
            return error("文件上传失败: " + e.getMessage());
        }
    }
}
